<?php
setlocale(LC_MONETARY, 'en_US');
require_once "../funciones.php";
require_once '../funciones/JSON.php';
$con = con_caweb();
if($_SESSION['caweb']['autenticado']!="si" || $_SESSION['caweb']['username'] == ""){
   echo "No puedes Ingresar sin autenticarte o Sesion Terminada ActualiceS la pagina";
   exit;
}
if($_REQUEST['opc'] == 'upt'){
    $obs = ",usuario ".$_SESSION['caweb']['username']." deja de facturar ".$_REQUEST['observacion']. " realizado el dia";
    $obs = trim($obs)." ";
    $ids = split(",",$_REQUEST['ids']);
    foreach ($ids as $value) {
        $sql = "update basefacturacion set observaciones= concat(observaciones,' ','$obs',now()),facturable = 'No' where id = ".$value;
        $result = mysql_query($sql) or die("Error SQL_UPT ".mysql_error().$sql);
    }
    echo "Actualizacion Exitosa";
}
else{
    $page = $_REQUEST['page']; // get the requested page
    $limit = $_REQUEST['rows']; // get how many rows we want to have into the grid
    $sidx = $_REQUEST['sidx']; // get index row - i.e. user click to sort
    $sord = $_REQUEST['sord']; // get the direction
    $sucursal = $_SESSION['caweb']['sucursalEquSinFact'];
    if(!$sidx) $sidx =1;

    $wh = "";
    $searchOn = Strip($_REQUEST['_search']);
    if($searchOn=='true') {
            $searchstr = Strip($_REQUEST['filters']);
            $wh= constructWhere($searchstr);
            //echo $wh;
    }

    $fechaCorte = ($_REQUEST['fechaCorte'] == "")? date("Y-m-d") : $_REQUEST['fechaCorte'];
    $nit = $_REQUEST['nit'];
    $dias = 1;
    $sql = "select  idfacturacion,interno,item,pedido,valoralquiler,fechadevolucion,fechaavisodevolucion,fechafacturar,fechainstalacion,ultimafactura,fechaultimafactura,sucursalfactura from vfacturables ";
    $sql .= "where (datediff('$fechaCorte',fechafacturar) >= $dias) ";
    $sql .= "and sucursalfactura in ($sucursal) ";
    $sql .= "and cliente = '$nit'".$wh;
    //echo $sql;    exit ;
    $result = mysql_query($sql) or die("Error SQL 1".  mysql_error());
    $count = mysql_numrows($result);

    if( $count >0 )
            $total_pages = ceil($count/$limit);
    else
            $total_pages = 0;
    //valida el limite de la consulta segun el numero de registros
    if ($page > $total_pages) $page=$total_pages;
            $start = $limit*$page - $limit;
    if ($start<0) $start = 0;

    //se construye la consulta principal
    $sql .= " ORDER BY $sidx $sord LIMIT $start , $limit";
    //echo $sql;exit;
    $result = mysql_query($sql) or die("Error SQL 2".  mysql_error().$sql);
    if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
        header("Content-type: application/xhtml+xml;charset=utf-8");
    } else {
        header("Content-type: text/xml;charset=utf-8");
    }
    $et = ">";
    echo "<?xml version='1.0' encoding='utf-8'?$et\n";
    echo "<rows>";
    echo "<page>".$page."</page>";
    echo "<total>".$total_pages."</total>";
    echo "<records>".$count."</records>"; // be sure to put text data in CDATA
    $facturarCliente = 0;
    while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {

        $fecEqu = $row['fechafacturar'];
        $fecAct = $fechaCorte;
        $pago = 0;
        if($fecAct > $fecEqu){
            $valorDia = $row['valoralquiler'] / 30;
            $mesEqu = date('n', strtotime($fecEqu)) ;
            $diaEqu = date('j', strtotime($fecEqu)) ;    //Se comienza a facturar un dia despues
            $anoEqu = date('Y', strtotime($fecEqu)) ;
            $mesAct = date('n', strtotime($fecAct)) ;
            $diaAct = date('j', strtotime($fecAct)) ;
            $anoAct = date('Y', strtotime($fecAct)) ;
            while($anoEqu < $anoAct || $mesEqu < $mesAct ){ // $diaAct != $diaEqu
                $fecha = mktime( 0, 0, 0, $mesEqu, 1, $anoEqu );
                if (!(date("t",$fecha) == $diaEqu)){ //Valida el ultimo dia del mes
                    $dia = 30 -$diaEqu;
                    if($dia > 0){
                        $pago = $pago + $dia * $valorDia;
                    }
                }
                /*else{
                    $pago = $pago + $valorDia;
                }*/
                $diaEqu = 0;
                if($mesEqu == 12){
                    $anoEqu ++;
                    $mesEqu = 1;
                }
                else
                    $mesEqu ++;
            }
            $fecha = mktime( 0, 0, 0, $mesAct, 1, $anoAct );
            $dia = (date("t",$fecha) == $diaAct)?30:$diaAct;
            $dia = abs($dia - $diaEqu);
            $pago = $pago + $dia * $valorDia;
        }
        $facturarCliente =  $facturarCliente + $pago;
        //Validacion para visualizar solo los campos solicitados
        if($con > $start && $con <= $limit){
            echo "<row id='".$row['idfacturacion']."'>";
            echo "<cell>". strtoupper($row['interno'])."</cell>";
            echo "<cell>". strtoupper($row['item'])."</cell>";
            echo "<cell>". strtoupper($row['pedido'])."</cell>";
            echo "<cell>". strtoupper($row['valoralquiler'])."</cell>";
            echo "<cell>". $pago."</cell>";
            echo "<cell>". strtoupper($row['fechadevolucion'])."</cell>";
            echo "<cell>". strtoupper($row['fechaavisodevolucion'])."</cell>";
            echo "<cell>". strtoupper($row['fechainstalacion'])."</cell>";
            echo "<cell>". strtoupper($row['ultimafactura'])."</cell>";
            echo "<cell>". strtoupper($row['fechaultimafactura'])."</cell>";
            echo "<cell>". strtoupper($row['sucursalfactura'])."</cell>";
            echo "</row>";
        }
    }
    echo "<userdata name='tvalor'>".money_format('%n',$facturarCliente)."</userdata>";
    echo "</rows>";
}

function Strip($value)
{
	if(get_magic_quotes_gpc() != 0)
  	{
    	if(is_array($value))
			if ( array_is_associative($value) )
			{
				foreach( $value as $k=>$v)
					$tmp_val[$k] = stripslashes($v);
				$value = $tmp_val;
			}
			else
				for($j = 0; $j < sizeof($value); $j++)
        			$value[$j] = stripslashes($value[$j]);
		else
			$value = stripslashes($value);
	}
	return $value;
}
function array_is_associative ($array)
{
    if ( is_array($array) && ! empty($array) )
    {
        for ( $iterator = count($array) - 1; $iterator; $iterator-- )
        {
            if ( ! array_key_exists($iterator, $array) ) { return true; }
        }
        return ! array_key_exists(0, $array);
    }
    return false;
}
function constructWhere($s){
    $json = new Services_JSON();
    $qwery = "";
	//['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    $qopers = array(
				  'eq'=>" = ",
				  'ne'=>" <> ",
				  'lt'=>" < ",
				  'le'=>" <= ",
				  'gt'=>" > ",
				  'ge'=>" >= ",
				  'bw'=>" LIKE ",
				  'bn'=>" NOT LIKE ",
				  'in'=>" IN ",
				  'ni'=>" NOT IN ",
				  'ew'=>" LIKE ",
				  'en'=>" NOT LIKE ",
				  'cn'=>" LIKE " ,
				  'nc'=>" NOT LIKE " );
    if ($s) {
        $prueba = $json->decode($s);
        $jsona = objecto2array($prueba);
        //$jsona = json_decode($s,true);
        if(is_array($jsona)){
			$gopr = $jsona['groupOp'];
			$rules = $jsona['rules'];
            $i =0;
            foreach($rules as $key=>$val) {
                $field = $val['field'];
                $op = $val['op'];
                $v = $val['data'];
				if($v && $op) {
	                $i++;
					// ToSql in this case is absolutley needed
					$v = ToSql($field,$op,$v);
					if ($i == 1) $qwery = " AND ";
					else $qwery .= " " .$gopr." ";
					switch ($op) {
						// in need other thing
					    case 'in' :
					    case 'ni' :
					        $qwery .= $field.$qopers[$op]." (".$v.")";
					        break;
						default:
					        $qwery .= $field.$qopers[$op].$v;
					}
				}
            }
        }
    }
    return $qwery;
}

function objecto2array($object)
{
  if(is_array($object) || is_object($object))
  {
    $array = array();
    foreach($object as $key => $value)
    {
      $array[$key] = objecto2array($value);
    }
    return $array;
  }
  return $object;
}

function ToSql ($field, $oper, $val) {
	// we need here more advanced checking using the type of the field - i.e. integer, string, float
	switch ($field) {
		case 'id':
			return intval($val);
			break;
		case 'amount':
		case 'tax':
		case 'total':
			return floatval($val);
			break;
		default :
			//mysql_real_escape_string is better
			if($oper=='bw' || $oper=='bn') return "'" . addslashes($val) . "%'";
			else if ($oper=='ew' || $oper=='en') return "'%" . addcslashes($val) . "'";
			else if ($oper=='cn' || $oper=='nc') return "'%" . addslashes($val) . "%'";
			else return "'" . addslashes($val) . "'";
	}
}
?>